package com.yc.navy.dayfresh.controller;

import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yc.navy.dayfresh.bean.AddrInfo;
import com.yc.navy.dayfresh.bean.MemberInfo;
import com.yc.navy.dayfresh.enums.ResultEnum;
import com.yc.navy.dayfresh.service.IAddrInfoService;
import com.yc.navy.dayfresh.util.ConstantInfo;
import com.yc.navy.dayfresh.util.StringUtil;
import com.yc.navy.dayfresh.vo.ResultVO;

@RestController
@RequestMapping("/addr")
public class AddrInfoController {
	@Autowired
	private IAddrInfoService addrInfoService; 
	
	
	private Long getLoginUser(HttpSession session) {
		Object obj = session.getAttribute(ConstantInfo.CURRENTLOGINMEMBERINFO);
		if(obj == null) {
			return null;
		}
		MemberInfo mf = (MemberInfo) obj;
		return mf.getMno();
	}
	
	@PostMapping("/add")
	public ResultVO add(HttpSession session,AddrInfo addr) {
		Long mno = this.getLoginUser(session);
		if(StringUtil.checkNull(mno)) {
			return new ResultVO(ResultEnum.LOGIN_ERROR);
		}
		
		addr.setMno(mno);
		String ano = UUID.randomUUID().toString();//没看懂
		addr.setAno(ano);
		
		int result = addrInfoService.add(addr);
		if(result == -1) {
			return new ResultVO(ResultEnum.CHECK_ERROR);
		}
		if(result > 0) {
			return new ResultVO(ResultEnum.SUCCESS,ano);
		}
		return new ResultVO(ResultEnum.ERROR);
	}
	
	@GetMapping("/finds")
	public ResultVO finds(HttpSession session) {
		Long mno = this.getLoginUser(session);
		if(StringUtil.checkNull(mno)) {
			return new ResultVO(ResultEnum.LOGIN_ERROR);
		}
		
		List<AddrInfo> list = addrInfoService.finds(mno);
		
		if(list !=null && !list.isEmpty()) {
			return new ResultVO(ResultEnum.SUCCESS,list);
		}
		
		return new ResultVO(ResultEnum.ERROR);
	}
}
